// store/user.js - 用户状态管理
import { defineStore } from 'pinia';
import { getToken, setToken, removeToken, getUserInfo, setUserInfo, removeUserInfo } from '../utils/storage.js';
import { wxLogin, logout as apiLogout, getUserInfo as apiGetUserInfo } from '../api/auth.js';
import userApi from '../api/user.js';

export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户信息
    userInfo: getUserInfo() || {},
    // 登录状态
    isLoggedIn: !!getToken(),
    // Token
    token: getToken() || '',
    // 用户积分
    points: 0,
    // 登录加载状态
    loading: false,
    // 错误信息
    error: null
  }),

  getters: {
    // 获取用户ID
    userId: (state) => state.userInfo.id || '',
    // 获取用户昵称
    nickname: (state) => state.userInfo.nickname || '游客',
    // 获取用户头像
    avatar: (state) => state.userInfo.avatar || '',
    // 获取用户手机号（隐藏中间4位）
    maskedPhone: (state) => {
      if (!state.userInfo.phone) return '';
      return state.userInfo.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
    },
    // 是否完善了个人信息
    isProfileCompleted: (state) => {
      return state.userInfo.nickname && state.userInfo.avatar;
    }
  },

  actions: {
    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo;
      setUserInfo(userInfo);
    },

    // 设置登录状态
    setLoggedIn(status) {
      this.isLoggedIn = status;
    },

    // 设置Token
    setToken(token) {
      this.token = token;
      setToken(token);
    },

    // 设置积分
    setPoints(points) {
      this.points = points;
    },

    // 微信登录
    async wechatLogin(code) {
      try {
        this.loading = true;
        this.error = null;

        const result = await wxLogin(code);
        
        if (result.code === 1) {
          this.setUserInfo(result.data.userInfo || {});
          this.setToken(result.data.token || '');
          this.setLoggedIn(true);
          
          // 获取用户积分
          this.fetchUserPoints();
          
          return true;
        } else {
          this.error = result.msg || '登录失败';
          return false;
        }
      } catch (error) {
        console.error('微信登录失败:', error);
        this.error = '登录失败，请稍后重试';
        return false;
      } finally {
        this.loading = false;
      }
    },

    // 退出登录
    async logout() {
      try {
        this.loading = true;
        
        // 调用退出登录接口（可选）
        await apiLogout();
        
        // 清除本地数据
        this.setUserInfo({});
        this.setToken('');
        this.setLoggedIn(false);
        this.setPoints(0);
        
        removeToken();
        removeUserInfo();
        
        return true;
      } catch (error) {
        console.error('退出登录失败:', error);
        // 即使接口调用失败，也清除本地数据
        this.setUserInfo({});
        this.setToken('');
        this.setLoggedIn(false);
        this.setPoints(0);
        
        removeToken();
        removeUserInfo();
        
        return true;
      } finally {
        this.loading = false;
      }
    },

    // 获取用户信息
    async fetchUserInfo() {
      try {
        this.loading = true;
        
        const result = await apiGetUserInfo();
        
        if (result.code === 1 && result.data?.userInfo) {
          this.setUserInfo(result.data.userInfo);
          return true;
        } else {
          // 如果获取失败且当前是登录状态，可能是token过期
          if (this.isLoggedIn) {
            this.logout();
          }
          return false;
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        return false;
      } finally {
        this.loading = false;
      }
    },

    // 获取用户积分
    async fetchUserPoints() {
      try {
        const result = await userApi.getUserPoints();
        
        if (result.code === 1 && result.data?.points !== undefined) {
          this.setPoints(result.data.points);
        }
      } catch (error) {
        console.error('获取用户积分失败:', error);
      }
    },

    // 更新用户信息
    updateUserInfo(updates) {
      const updatedUserInfo = { ...this.userInfo, ...updates };
      this.setUserInfo(updatedUserInfo);
    },

    // 增加积分
    addPoints(points) {
      this.points += points;
    },

    // 减少积分
    reducePoints(points) {
      this.points = Math.max(0, this.points - points);
    },

    // 重置状态
    resetState() {
      this.userInfo = {};
      this.isLoggedIn = false;
      this.token = '';
      this.points = 0;
      this.loading = false;
      this.error = null;
      
      removeToken();
      removeUserInfo();
    },

    // 检查登录状态并刷新用户信息
    async checkAndRefresh() {
      if (this.isLoggedIn) {
        await this.fetchUserInfo();
        await this.fetchUserPoints();
      }
    }
  }
});